package top.xiaoshuaila.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.xiaoshuaila.pojo.MailConstants;
import top.xiaoshuaila.pojo.MailLog;
import top.xiaoshuaila.service.IMailLogService;


@Configuration
public class RabbitMQConfig {

    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;
    @Autowired
    private IMailLogService  mailLogService;


    @Bean
    public RabbitTemplate rabbitTemplate(){
        //设置RabbitTemplate的连接工厂
        RabbitTemplate rabbitTemplate =
                new RabbitTemplate(cachingConnectionFactory);
        /*
        * data:CorrelationData类型参数
        * ack:确认结果
        * cause:失败原因
        * */

        //该方法作用是对消费端发过来的确认ack进行处理
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData data,
                                boolean ack, String cause) {
                String msgid=data.getId();
                //如果返回成功的确认ack,将maillog表中的状态设为1
                if(ack){
                    mailLogService.update(new UpdateWrapper<MailLog>()
                    .set("status",1).eq("msgId",msgid));
                    System.out.println("消息发送成功!:"+msgid);
                }
            }
        });
        //该方法的作用是对消息发送失败后做出处理,这里的作用是发送失败后输出一次错误信息
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                System.out.println("消息发送失败!"+returnedMessage.getMessage().getBody());
            }
        });

        return rabbitTemplate;
    }

    //创建一个队列
    @Bean
    public Queue queue(){
        return new Queue(MailConstants.QUEUE_NAME);
    }
    //创建一个交换机
    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange(MailConstants.EXCHANGE_NAME);
    }
    //将队列绑定交换机
    @Bean
    public Binding binding (){
        return BindingBuilder
                .bind(queue())
                .to(directExchange())
                .with(MailConstants.ROUTING_NAME);
    }
}
